//请求的地址
const HTTP = "";

// get请求
const get = (url, data = {}) => {
	return request(url, "GET", data);
};
// post请求
const post = (url, data = {}) => {
	return request(url, "POST", data);
};

/**
 * 网络请求
 * @param {String} url 请求的地址
 * @param {'GET' | 'POST'} method 请求的方式
 * @param {Object} data 请求的参数
 * @param {Boolean} hidden 是否显示挡板
 */
const request = (url, method, data) => {
	uni.showLoading({
		title: "请求中",
		mask: true,
	});
	return new Promise((success, fail) => {
		let token = "";
		uni.request({
			url: HTTP + url,
			method,
			header: {
				token,
			},
			data,
			success: (res) => {
				uni.hideLoading();
				uni.stopPullDownRefresh();
				let data = res.data;
				console.log("网络请求的所有数据", data, url, token, res);
				if (data.code == 1) {
					success(data);
				} else {
					// st.show(data.msg)
					fail(data);
				}
			},
			fail: (res) => {
				uni.hideLoading();
				uni.stopPullDownRefresh();
				// st.show("服务器请求失败，请稍后重试")
			},
		});
	});
};

const upload = (file) => {
	uni.showLoading({
		title: "上传中",
		mask: true,
	});
	let promise = new Promise((success, fail) => {
		uni.uploadFile({
			filePath: file,
			name: "file",
			url: HTTP + "common/upload",
			success(res) {
				uni.hideLoading();
				// console.log("上传文件", res);
				if (res.errMsg == "uploadFile:ok") {
					let data = JSON.parse(res.data);
					if (data.code == 1) {
						success(data);
					} else {
						fail(data);
					}
				}
			},
			fail: (res) => {
				uni.hideLoading();
			},
		});
	});
	return promise;
};

export default {
	get,
	post,
	upload,
};
